#include "general.h"

#include <cfilefilter.h>
#include <cfolder.h>

CMetaDataIndex *CMetaDataIndex::mIndex;

CMetaDataIndex::CMetaDataIndex()
{
	mURL=CURL::GetHome()+".buola"+"metadata";
	Load();
}

CMetaDataIndex::~CMetaDataIndex()
{
}

void CMetaDataIndex::Load()
{
	PFileFilter lFilter=new CRegexFileFilter("*.metadata");
	PFolder lFolder=CFolder::Get(mURL);
	std::vector<CURL> lURLs;
	lFolder->GetAllURLs(lURLs,lFilter);

	for(int i=0;i<lURLs.size();i++)
	{
		mFileNames.insert(lURLs[i].GetName());
	}
}

std::string CMetaDataIndex::GetFilenameFor(const std::string &pFolder,bool pCreate)
{
	if(mFolderToFile.count(pFolder))
		return mFolderToFile[pFolder];

	std::string lURIEscaped=uri_escape(pFolder);
	lURIEscaped+=".metadata";

	if(mFileNames.count(lURIEscaped))
	{
		mFolderToFile[pFolder]=lURIEscaped;
		return lURIEscaped;
	}
	else if(pCreate)
	{
		mFolderToFile[pFolder]=lURIEscaped;
		mFileNames.insert(lURIEscaped);
		return lURIEscaped;
	}
	else
	{
		return std::string();
	}
}
